from django.shortcuts import render, redirect
from django.contrib import admin, messages
from django.core.exceptions import PermissionDenied

from .core import SettingsWrapper as settings_wrapper


def settings(req):
    context = dict(admin.site.each_context(req))

    user = req.user

    # Checking permissions
    if not user.is_superuser:
        raise PermissionDenied()

    if req.method == 'POST':
        if settings_wrapper.handle_save(req):
            messages.success(req, "Saved successfully.")
            return redirect('admin:settings')
        else:
            message.error(req, 'Invalid data!')

    context.update({
        'settings_wrapper': settings_wrapper,
        'tab_list': settings_wrapper._tab_list
    })

    return render(req, 'settings.html', context)
